from models.user import User
from util.log import Log
from util.redis import Redis
from common.const import BaseConstant

async def loginByUsername(username: str, password: str):
    try:
        user = await User.filter(username=username, password=password, banned=0).first()
        return user
    except Exception as e:
        Log.error('通过 username 进行 login 异常:', e)

async def saveUser(user: User):
    try:
        await User.save(user)
    except Exception as e:
        Log.error('保存 user 异常', e)
        raise e

async def createUser(user: dict):
    try:
        return await User.create(**user)
    except Exception as e:
        Log.error('创建 user 异常', e)
        raise e

async def hasUsername(username: str):
    try:
        key: str = BaseConstant.REGISTER_USERNAME_KEY % username
        redisObj = Redis.getItem(key)
        if redisObj == None:
            return False
        else:
            return True
    except Exception as e:
        Log.error('检查 username 是否存在', e)

async def getUserByToken(token: str):
    try:
        user = await User.filter(token=token).first()
        # user = await User.filter(token=token).first().values("id", "username")
        return user
    except Exception as e:
        Log.error('通过 token 获取 user 异常', e)

async def getUserById(id: int):
    try:
        user = await User.filter(id=id).first()
        return user
    except Exception as e:
        Log.error('通过 id 获取 user 异常', e)

async def getListByIds(ids: list):
    try:
        userList = await User.filter(id__in=ids).all().values("id", "username", "avatar")
        return userList
    except Exception as e:
        Log.error('通过 id List 获取 user List 异常', e)

async def SearchUsername(username: str):
    try:
        userList = await User.filter(username__icontains=username).all().values("id", "username")
        return userList
    except Exception as e:
        Log.error('模糊查询 username List 异常', e)

async def getUserByUsername(username: str):
    try:
        user = await User.filter(username=username).first()
        return user
    except Exception as e:
        Log.error('通过 username 查询 user 异常', e)

